package com.benmu.framework.event.camera;

import android.Manifest;
import android.content.Context;

import com.benmu.framework.constant.Constant;
import com.benmu.framework.constant.WXEventCenter;
import com.benmu.framework.manager.ManagerFactory;
import com.benmu.framework.manager.impl.MyFileManager;
import com.benmu.framework.manager.impl.ParseManager;
import com.benmu.framework.manager.impl.PersistentManager;
import com.benmu.framework.manager.impl.dispatcher.DispatchEventManager;
import com.benmu.framework.model.UploadFileBean;
import com.benmu.framework.model.UploadResultBean;
import com.benmu.framework.model.WeexEventBean;
import com.benmu.framework.utils.JsPoster;
import com.benmu.framework.utils.PermissionUtils;
import com.benmu.wxbase.EventGate;
import com.squareup.otto.Subscribe;
import com.taobao.weex.bridge.JSCallback;

/***
 *  xum  add  fileupload
 */
public class EventFile extends EventGate {
    private JSCallback mPickCallback;

    @Override
    public void perform(Context context, WeexEventBean weexEventBean, String type) {

        String params = weexEventBean.getJsParams();
        if (WXEventCenter.EVENT_FILE_PICK.equals(type)) {
            pick(weexEventBean.getJsParams(), context, weexEventBean.getJscallback());
        }
    }

    public void pick(String json, Context context, JSCallback jsCallback) {
        //Manifest.permission.READ_EXTERNAL_STORAGE 权限申请
        if (!PermissionUtils.checkPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            return;
        }
        mPickCallback = jsCallback;
        UploadFileBean bean = ManagerFactory.getManagerService(ParseManager.class).parseObject
                (json, UploadFileBean.class);
        ManagerFactory.getManagerService(DispatchEventManager.class).getBus().register(this);
        MyFileManager myFileManager = ManagerFactory.getManagerService(MyFileManager.class);
        myFileManager.pickFile(context, bean, Constant.FileConstants.FILE_NOT_UPLOADER_PICKER);
//         if (bean.maxCount > 0) {
//
//        }
    }

    @Subscribe
    public void OnUploadResult(UploadResultBean uploadResultBean) {
        if (uploadResultBean != null && mPickCallback != null) {
            JsPoster.postSuccess(uploadResultBean.data, mPickCallback);
        }

        ManagerFactory.getManagerService(DispatchEventManager.class).getBus().unregister(this);
        mPickCallback = null;
//        ManagerFactory.getManagerService(PersistentManager.class).deleteCacheData(Constant
//                .ImageConstants.UPLOAD_IMAGE_BEAN);
        ManagerFactory.getManagerService(PersistentManager.class).deleteCacheData(Constant
                .FileConstants.UPLOAD_FILE_BEAN);
    }


}

